<?php

namespace app\admin\controller\xykeep\user;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\xykeep\Course as CourseModel;
use app\admin\model\xykeep\user\CourseLog as UserCourseLogModel;
use app\admin\model\xykeep\coach\Student as StudentModel;
use app\admin\model\xykeep\User as UserModel;
use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\db\exception\BindParamException;
use think\exception\DbException;
use addons\xykeep\service\Store as StoreService;

/**
 * 用户课程
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{

    /**
     * Course模型对象
     * @var \app\admin\model\xykeep\user\Course
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'id,user.nickname,coach.realname,store.name,course.name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xykeep\user\Course;

    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;

        
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $fieldArr = [
            '会员手机号' => 'mobile',
            '会员姓名' => 'name',
            '课程ID' => 'course_id',
            '课程节数' => 'nums',
            '购课费用' => 'money',
        ];

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }


            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }


        try {
            
            foreach($insert as $params){

                $user = UserModel::where(['mobile'=>$params['mobile']])->find();

                if(empty($user)){
                    continue;
                }
                $user->nickname = $params['name'];
                $user->save();

                //课程
                $course = CourseModel::get($params['course_id']);

                //用户课程
                $userCourse = $this->model::where([
                    'store_id' => $course['store_id'],
                    'coach_id' => $course['coach_id'],
                    'course_id' => $params['course_id'],
                    'user_id' => $user['id'],
                    'type' => $course['type'],
                ])->find();

                if(empty($userCourse)){
                    $userCourse = $this->model::create([
                        'store_id' => $course['store_id'],
                        'coach_id' => $course['coach_id'],
                        'course_id' => $params['course_id'],
                        'user_id' => $user['id'],
                        'name' => $course['name'],
                        'type' => $course['type'],
                        'image' => cdnurl($course['image']),
                        'nums' => $params['nums'],
                        'money' => $params['money'],
                    ]);
                }else{
                    $userCourse->nums = $userCourse['nums'] + $params['nums'];
                    $userCourse->money = $userCourse['money'] + $params['money'];
                    $userCourse->save();
                }

                // 添加用户课程记录
                UserCourseLogModel::addLog([
                    'user_course_id' => $userCourse['id'],
                    'nums' => $params['nums'],
                    'money' => $params['money'],
                    'type' => 'sys',
                    'reoson' => '后台导入',
                ]);

                $student = StudentModel::where(['user_id'=>$user['id'],'coach_id'=>$course['coach_id']])->find();
                if(empty($student)){
                    StudentModel::create([
                        'user_id'   => $user['id'],
                        'coach_id'  => $course['coach_id'],
                        'reason'    => 'sys_'.$course['type'],
                        'service_id'=> $userCourse['id']
                    ]);
                }

            }


        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }

    /**
     * 减课
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function reduce($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if($params['nums'] > $row['nums']){
            $this->error(__('减课节数输入错误', ''));
        }

        if($params['money'] < 0 || $params['money'] > $row['money']  ){
            $this->error(__('减课退费输入错误', ''));
        }

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            // 添加用户课程记录
            UserCourseLogModel::addLog([
                'user_course_id' => $ids,
                'nums' => -$params['nums'],
                'money' => $params['money'],
                'type' => 'sys',
                'reoson' => $params['reason'],
            ]);

            // 添加门店收入和记录
            $storeService =  new StoreService($row['store_id']);
            $storeService->money(-$params['money'],'sys_rc',$row['id']);

            $result = $row->allowField(true)->save(['nums'=>$row['nums']-$params['nums'],'money'=>$row['money']-$params['money']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 加课
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function increase($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if($params['nums']<=0){
            $this->error(__('增加节数输入错误', ''));
        }

        if($params['money']<=0){
            $this->error(__('课程费用输入错误', ''));
        }

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            //增加课程销量
            $course = CourseModel::get($row['course_id']);
            $course->setInc('sales',$params['nums']);

            // 添加用户课程记录
            UserCourseLogModel::addLog([
                'user_course_id' => $ids,
                'nums' => $params['nums'],
                'money' => $params['money'],
                'type' => 'sys',
                'reoson' => $params['reason'],
            ]);

            // 添加门店收入和记录
            $storeService =  new StoreService($row['store_id']);
            $storeService->money($params['money'],'sys_ic',$row['id']);

            $result = $row->allowField(true)->save(['nums'=>$row['nums']+$params['nums'],'money'=>$row['money']+$params['money']]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if(empty($params['store_id'])){
            $this->error(__('请选择上课门店', ''));
        }

        if(empty($params['coach_id'])){
            $this->error(__('请选择上课教练', ''));
        }

        if(empty($params['course_id'])){
            $this->error(__('请选择购买课程', ''));
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            //课程
            $course = CourseModel::get($params['course_id']);
            //增加课程销量
            $course->setInc('sales',$params['nums']);

            //用户课程
            $userCourse = $this->model::where([
                'store_id' => $course['store_id'],
                'coach_id' => $course['coach_id'],
                'course_id' => $params['course_id'],
                'user_id' => $params['user_id'],
                'type' => $course['type'],
            ])->find();

            if(empty($userCourse)){
                $userCourse = $this->model::create([
                    'store_id' => $course['store_id'],
                    'coach_id' => $course['coach_id'],
                    'course_id' => $params['course_id'],
                    'user_id' => $params['user_id'],
                    'name' => $course['name'],
                    'type' => $course['type'],
                    'image' => cdnurl($course['image']),
                    'nums' => $params['nums'],
                    'money' => $params['money'],
                ]);
            }else{
                $userCourse->nums = $userCourse['nums'] + $params['nums'];
                $userCourse->money = $userCourse['money'] + $params['money'];
                $userCourse->save();
            }

            // 添加用户课程记录
            UserCourseLogModel::addLog([
                'user_course_id' => $userCourse['id'],
                'nums' => $params['nums'],
                'money' => $params['money'],
                'type' => 'sys',
                'reoson' => '后台添加',
            ]);

            // 增加教练学员
            $student = StudentModel::where(['user_id'=>$params['user_id'],'coach_id'=>$course['coach_id']])->find();
            if(empty($student)){
                StudentModel::create([
                    'user_id'   => $params['user_id'],
                    'coach_id'  => $course['coach_id'],
                    'reason'    => 'sys_'.$course['type'],
                    'service_id'=> $userCourse['id']
                ]);
            }

            // 添加门店收入和记录
            $storeService =  new StoreService($course['store_id']);
            $storeService->money($params['money'],'sys_ac',$userCourse['id']);

            
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        $this->success();
    }



    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','courseDetail','coach','store'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



}
